package com.ck.company.controller;

import com.ck.company.service.CpFileService;
import com.ck.config.CustomProperties;
import com.ck.constant.FileConstant;
import com.ck.constant.RequestConstant;
import com.ck.constant.ResponseConstant;
import com.ck.exception.ControllerException;
import com.ck.exception.ServiceException;
import com.ck.model.common.File;
import com.ck.model.common.User;
import com.ck.model.common.page.PageInfo;
import com.ck.model.common.sys.JsonResponse;
import com.ck.model.company.vo.CpFileListVO;
import com.ck.util.HttpUtils;
import com.google.common.collect.Lists;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 文件Controller
 *
 * @author dxy
 * @date 2018/9/13 10:53
 */
@Controller
@RequestMapping(value = "/cpFile")
public class CpFileController {
	private static Logger logger = LoggerFactory.getLogger(CpFileController.class);
	@Autowired
	private CpFileService cpFileService;
	@Autowired
	private CustomProperties customProperties;
	/**
	 * 上传文档文件
	 */
	@ResponseBody
	@RequestMapping(value = "/uploadDocumentFile")
	public Object uploadDocumentFile(@Param("files") MultipartFile files, HttpServletRequest request) {
		try {
			//文档文件全名（包含扩展名）
			String originalFilename = files.getOriginalFilename();
			if (StringUtils.isBlank(originalFilename)) {
				return  new JsonResponse(ResponseConstant.CODE_FAIL, "文档名称不能为空");
			}
			//文档文件后缀
			String extension = FilenameUtils.getExtension(originalFilename);
			//校验文件后缀格式是否是音频后缀格式
			if (!FileConstant.DOCUMENT_SUFFIX_LIST.contains(extension)) {
				return  new JsonResponse(ResponseConstant.CODE_FAIL, "文件格式不正确，请上传文档格式文件");
			}
			//文档文件名称
			String fileName = originalFilename.replaceAll("." + extension, "");
			if (StringUtils.isBlank(fileName.trim())) {
				return  new JsonResponse(ResponseConstant.CODE_FAIL, "文档文件名称不能为空");
			}
			//登录用户
			User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
			//商家编码
			String companyCode = loginUser.getCompanyCode();
			//云存储目录
			String cloudFileDir = companyCode + "/document/";
			//文件类型-音频文件
			Integer fileType = FileConstant.FILE_TYPE_DOCUMENT;
			//返回列表
			List msgList = Lists.newArrayList();
			//上传至华为云
			Map<String, Object> fileMap = cpFileService.uploadFile(files, fileType, companyCode, cloudFileDir, false);
			msgList.add(fileMap);
			//保存文件信息到数据库
			File file = new File();
			file.setCompanyCode(companyCode);
			file.setFileName(String.valueOf(fileMap.get(FileConstant.FILE_NAME)));
			file.setUrl(String.valueOf(fileMap.get(FileConstant.URL)));
			file.setMd5(String.valueOf(fileMap.get(FileConstant.MD5)));
			file.setSize(Long.valueOf(String.valueOf(fileMap.get(FileConstant.SIZE))));
			file.setFileSuffix(String.valueOf(fileMap.get(FileConstant.FILE_SUFFIX)));
			file.setFileType(fileType);
			cpFileService.saveFile(file, loginUser, HttpUtils.getRemortIP(request));
			return msgList;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("CpFileController uploadDocumentFile 上传文档文件失败：" + e.getMessage());
			return new ControllerException("上传文档文件失败，请联系管理员");
		}
	}

	/**
	 * 上传音频文件
	 */
	@ResponseBody
	@RequestMapping(value = "/uploadAudioFile")
	public Object uploadAudioFile(@Param("files") MultipartFile files, HttpServletRequest request) {
		//文件类型-音频文件
		Integer fileType = FileConstant.FILE_TYPE_AUDIO;
		try {
			//验证音频文件大小
			Long audioMaxSize = customProperties.getAudioMaxSize();
			if (audioMaxSize < files.getSize()) {
				return  new JsonResponse(ResponseConstant.CODE_FAIL, "音频文件大小不能超过50MB");
			}
			//音频文件全名（包含扩展名）
			String originalFilename = files.getOriginalFilename();
			if (StringUtils.isBlank(originalFilename)) {
				return  new JsonResponse(ResponseConstant.CODE_FAIL, "音频名称不能为空");
			}
			//音频文件后缀
			String extension = FilenameUtils.getExtension(originalFilename);
			//校验文件后缀格式是否是音频后缀格式
			if (!FileConstant.AUDIO_SUFFIX_LIST.contains(extension)) {
				return  new JsonResponse(ResponseConstant.CODE_FAIL, "文件格式不正确，请上传音频格式文件");
			}
			//音频文件名称
			String videoName = originalFilename.replaceAll("." + extension, "");
			if (StringUtils.isBlank(videoName.trim())) {
				return  new JsonResponse(ResponseConstant.CODE_FAIL, "音频文件名称不能为空");
			}
			//登录用户
			User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
			//商家编码
			String companyCode = loginUser.getCompanyCode();
			//云存储目录
			String cloudFileDir = companyCode + "/audio/";
			//返回列表
			List msgList = Lists.newArrayList();
			Map<String, Object> fileMap = cpFileService.uploadFile(files, fileType, companyCode, cloudFileDir, true);
			msgList.add(fileMap);
			//保存文件信息到数据库
			File file = new File();
			file.setCompanyCode(companyCode);
			file.setFileName(String.valueOf(fileMap.get(FileConstant.FILE_NAME)));
			file.setUrl(String.valueOf(fileMap.get(FileConstant.URL)));
			file.setMd5(String.valueOf(fileMap.get(FileConstant.MD5)));
			file.setDuration(Long.valueOf(String.valueOf(fileMap.get(FileConstant.DURATION))));
			file.setSize(Long.valueOf(String.valueOf(fileMap.get(FileConstant.SIZE))));
			file.setFileSuffix(String.valueOf(fileMap.get(FileConstant.FILE_SUFFIX)));
			file.setFileType(fileType);
			cpFileService.saveFile(file, loginUser, HttpUtils.getRemortIP(request));
			return msgList;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("CpFileController uploadAudioFile 上传音频文件失败：" + e.getMessage());
			return new ControllerException("上传音频文件失败，请联系管理员");
		}
	}

	/**
	 * 列表
	 */
	@RequestMapping("/list")
	public String listFile(String fileName, Integer fileType, Integer pageNum, Integer pageSize, Model model, HttpServletRequest request) {
		User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
		String companyCode = loginUser.getCompanyCode();
		String returnURL = "error/404";
		//文档界面
		if (FileConstant.FILE_TYPE_DOCUMENT == fileType) {
			returnURL = "cp/cp_document_list";
		}
		//音频界面
		if (FileConstant.FILE_TYPE_AUDIO == fileType) {
			returnURL = "cp/cp_audio_list";
		}
		try {
			PageInfo<CpFileListVO> pageInfo = cpFileService.listFile(companyCode, fileType, fileName, pageNum, pageSize);
			model.addAttribute("fileName", fileName);
			model.addAttribute("fileList", pageInfo.getList());
			model.addAttribute("pageNum", pageInfo.getPageNum());
			model.addAttribute("pageSize", pageInfo.getPageSize());
			model.addAttribute("total", pageInfo.getTotal());
		} catch (ServiceException e) {
			e.printStackTrace();
			logger.error("CpFileController listFile 获取列表失败：" + e.getMessage());
			return "error/404";
		}
		return returnURL;
	}

	/**
	 * 重命名
	 */
	@ResponseBody
	@RequestMapping(value = "/rename")
	public Object rename(Long fileId, String fileNewName, HttpServletRequest request) {
		if (fileId == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "ID不能为空,请联系管理员");
		}
		if (StringUtils.isBlank(fileNewName)) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "名称不能为空，请输入名称");
		}
		try {//校验文件是否存在
			File file = cpFileService.getFileById(fileId);
			if (file == null) {
				return new JsonResponse(ResponseConstant.CODE_FAIL, "文件不存在，请联系管理员");
			}
			Integer fileType = file.getFileType();
			if (fileType == null) {
				return new JsonResponse(ResponseConstant.CODE_FAIL, "文件类型不能为空，请联系管理员");
			}
			//登录用户
			User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
			//商家编码
			String companyCode = loginUser.getCompanyCode();
			//云存储目录,根据具体类型而定，如果有多个类型，请在下面加条件
			String cloudFileDir = "";
			if (FileConstant.FILE_TYPE_DOCUMENT == fileType) {
				cloudFileDir = companyCode + "/document/";
			} else if (FileConstant.FILE_TYPE_AUDIO == fileType) {
				cloudFileDir = companyCode + "/audio/";
			}
			//将云上的文件下载到本地，对下载的文件重新命名，并将重新命名后的文件上传至云上
			Map<String, Object> fileMap = cpFileService.renameFileAndUpload(fileId, fileNewName, cloudFileDir);
			//将文件写入数据库
			File newFile = new File();
			newFile.setUrl(String.valueOf(fileMap.get(FileConstant.URL)));
			newFile.setFileName(fileNewName);
			newFile.setFileId(fileId);
			cpFileService.updateFileById(newFile, loginUser, HttpUtils.getRemortIP(request), fileType);
		} catch (ServiceException e) {
			e.printStackTrace();
			logger.error("CpFileController rename 重命名失败：" + e.getMessage());
			return new ControllerException("重命名失败, 请联系管理员");
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("CpFileController rename 重命名失败：" + e.getMessage());
			return new ControllerException("重命名失败, 请联系管理员");
		}
		return "重命成功";
	}

	/**
	 * 删除
	 */
	@ResponseBody
	@RequestMapping(value = "delete")
	public Object delete(Long fileId, HttpServletRequest request) {
		if (fileId == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "ID不能为空,请联系管理员");
		}
		//登录用户
		User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
		String remoteIp = HttpUtils.getRemortIP(request);
		try {
			//删除文件
			cpFileService.deleteFile(fileId, loginUser, remoteIp);
		} catch (ServiceException e) {
			e.printStackTrace();
			logger.error("CpFileController rename 删除失败：" + e.getMessage());
			return new ControllerException("删除失败，请联系管理员");
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("CpFileController rename 删除失败：" + e.getMessage());
			return new ControllerException("删除失败，请联系管理员");
		}
		return "删除成功";
	}
}
